package com.vehiclesecure.config;

import com.vehiclesecure.service.VehicleUserSyncService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

/**
 * 车辆用户同步运行器
 * 在应用启动时自动执行车辆用户关联同步
 */
@Component
@Order(2) // 在数据初始化之后执行
public class VehicleUserSyncRunner implements CommandLineRunner {

    private final VehicleUserSyncService vehicleUserSyncService;

    @Autowired
    public VehicleUserSyncRunner(VehicleUserSyncService vehicleUserSyncService) {
        this.vehicleUserSyncService = vehicleUserSyncService;
    }

    @Override
    public void run(String... args) throws Exception {
        System.out.println("开始执行车辆用户同步...");
        
        try {
            // 同步所有车辆的用户关联
            vehicleUserSyncService.syncAllVehicleUsers();
            
            // 修复孤立车辆
            vehicleUserSyncService.fixOrphanedVehicles();
            
            System.out.println("车辆用户同步完成！");
        } catch (Exception e) {
            System.err.println("车辆用户同步失败: " + e.getMessage());
            e.printStackTrace();
        }
    }
}